import React, {
  createContext,
  useContext,
  useReducer,
  useEffect,
  ReactNode,
} from "react";
import { message } from "antd";
import request from "../utils/request";

// 用户信息接口
export interface User {
  id: number;
  name: string;
  email: string;
  phone?: string;
  type: "student" | "teacher" | "admin";
  avatar?: string;
  teacherNo?: string;
  studentId?: string;
  classId?: number;
  className?: string;
  subject?: string;
  grade?: string;
  gender?: number;
  bio?: string;
  settings?: {
    theme?: "light" | "dark";
    fontSize?: "small" | "medium" | "large";
    notifications?: boolean;
  };
  permissions?: string[];
}

// 认证状态接口
interface AuthState {
  isAuthenticated: boolean;
  user: User | null;
  token: string | null;
  loading: boolean;
  permissions: string[];
}

// 认证操作类型
type AuthAction =
  | { type: "LOGIN_START" }
  | { type: "LOGIN_SUCCESS"; payload: { user: User; token: string } }
  | { type: "LOGIN_FAILURE"; payload: string }
  | { type: "LOGOUT" }
  | { type: "UPDATE_USER"; payload: Partial<User> }
  | { type: "SET_LOADING"; payload: boolean }
  | { type: "RESTORE_AUTH"; payload: { user: User; token: string } };

// 认证上下文接口
interface AuthContextType {
  state: AuthState;
  login: (credentials: LoginCredentials) => Promise<void>;
  logout: () => void;
  updateUser: (updates: Partial<User>) => void;
  hasPermission: (permission: string) => boolean;
  hasRole: (role: string) => boolean;
  refreshUserInfo: () => Promise<void>;
}

// 登录凭据接口
interface LoginCredentials {
  username: string;
  password: string;
  remember?: boolean;
}

// 初始状态
const initialState: AuthState = {
  isAuthenticated: false,
  user: null,
  token: null,
  loading: true,
  permissions: [],
};

// Reducer
const authReducer = (state: AuthState, action: AuthAction): AuthState => {
  switch (action.type) {
    case "LOGIN_START":
      return {
        ...state,
        loading: true,
      };

    case "LOGIN_SUCCESS":
      return {
        ...state,
        isAuthenticated: true,
        user: action.payload.user,
        token: action.payload.token,
        loading: false,
        permissions: action.payload.user.permissions || [],
      };

    case "LOGIN_FAILURE":
      return {
        ...state,
        isAuthenticated: false,
        user: null,
        token: null,
        loading: false,
        permissions: [],
      };

    case "LOGOUT":
      return {
        ...initialState,
        loading: false,
      };

    case "UPDATE_USER":
      return {
        ...state,
        user: state.user ? { ...state.user, ...action.payload } : null,
      };

    case "SET_LOADING":
      return {
        ...state,
        loading: action.payload,
      };

    case "RESTORE_AUTH":
      return {
        ...state,
        isAuthenticated: true,
        user: action.payload.user,
        token: action.payload.token,
        loading: false,
        permissions: action.payload.user.permissions || [],
      };

    default:
      return state;
  }
};

// 创建上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者组件
export const AuthProvider: React.FC<{ children: ReactNode }> = ({
  children,
}) => {
  const [state, dispatch] = useReducer(authReducer, initialState);

  // 组件挂载时恢复认证状态
  useEffect(() => {
    restoreAuthState();
  }, []);

  // 恢复认证状态
  const restoreAuthState = async () => {
    try {
      const token = localStorage.getItem("token");
      const userStr = localStorage.getItem("currentUser");

      if (token && userStr) {
        const user = JSON.parse(userStr);
        dispatch({ type: "RESTORE_AUTH", payload: { user, token } });

        // 验证token是否仍然有效
        try {
          await request.get("/api/v1/auth/verify");
        } catch (error) {
          // token无效，清除认证状态
          logout();
        }
      } else {
        dispatch({ type: "SET_LOADING", payload: false });
      }
    } catch (error) {
      console.error("恢复认证状态失败:", error);
      dispatch({ type: "SET_LOADING", payload: false });
    }
  };

  // 登录
  const login = async (credentials: LoginCredentials) => {
    dispatch({ type: "LOGIN_START" });

    try {
      const response = await request.post("/api/v1/auth/login", credentials);

      if (response.code === 0) {
        const { user, token } = response.data;

        // 保存到localStorage
        localStorage.setItem("token", token);
        localStorage.setItem("currentUser", JSON.stringify(user));

        if (credentials.remember) {
          localStorage.setItem("rememberMe", "true");
        }

        dispatch({ type: "LOGIN_SUCCESS", payload: { user, token } });
        message.success("登录成功");
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      const errorMessage = error.message || "登录失败";
      dispatch({ type: "LOGIN_FAILURE", payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 登出
  const logout = () => {
    try {
      // 调用登出API（可选）
      request.post("/api/v1/auth/logout").catch(() => {
        // 忽略登出API错误
      });
    } catch (error) {
      // 忽略登出错误
    }

    // 清除本地存储
    localStorage.removeItem("token");
    localStorage.removeItem("currentUser");
    localStorage.removeItem("rememberMe");

    dispatch({ type: "LOGOUT" });
    message.success("已安全退出");
  };

  // 更新用户信息
  const updateUser = (updates: Partial<User>) => {
    if (state.user) {
      const updatedUser = { ...state.user, ...updates };
      localStorage.setItem("currentUser", JSON.stringify(updatedUser));
      dispatch({ type: "UPDATE_USER", payload: updates });
    }
  };

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    if (!state.user || !state.permissions) return false;
    
    // 超级管理员拥有所有权限
    if (state.user.type === "admin") {
      return true;
    }
    
    return state.permissions.includes(permission);
  };

  // 检查角色
  const hasRole = (role: string): boolean => {
    if (!state.user) return false;
    return state.user.type === role;
  };

  // 刷新用户信息
  const refreshUserInfo = async () => {
    try {
      const response = await request.get("/api/v1/auth/userinfo");
      if (response.code === 0) {
        const user = response.data;
        localStorage.setItem("currentUser", JSON.stringify(user));
        dispatch({ type: "UPDATE_USER", payload: user });
      }
    } catch (error) {
      console.error("刷新用户信息失败:", error);
    }
  };

  const contextValue: AuthContextType = {
    state,
    login,
    logout,
    updateUser,
    hasPermission,
    hasRole,
    refreshUserInfo,
  };

  return (
    <AuthContext.Provider value={contextValue}>{children}</AuthContext.Provider>
  );
};

// 使用认证上下文的Hook
export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};

// 权限检查组件
interface PermissionGuardProps {
  permission?: string;
  role?: string;
  fallback?: ReactNode;
  children: ReactNode;
}

export const PermissionGuard: React.FC<PermissionGuardProps> = ({
  permission,
  role,
  fallback = null,
  children,
}) => {
  const { hasPermission, hasRole } = useAuth();

  const hasAccess = () => {
    if (permission && !hasPermission(permission)) return false;
    if (role && !hasRole(role)) return false;
    return true;
  };

  return hasAccess() ? <>{children}</> : <>{fallback}</>;
};
